<template>
    <div class="main-container">
        <el-card class="card !border-none" shadow="never">
            <!-- 团队绩效奖励 -->
            <div class="flex justify-between items-center">
                <span class="text-page-title">{{ pageName }}</span>
            </div>
            <el-card class="card my-[10px] !border-none table-search-wrap" shadow="never">
                <el-form :inline="true" :model="fenxiaoTable.searchParam" ref="searchFormRef">
                    <el-form-item label="会员信息" prop="keyword">
                        <el-input v-model.trim="fenxiaoTable.searchParam.keyword" placeholder="请输入会员昵称或者手机号" maxlength="60" />
                    </el-form-item>
                    <el-form-item label="会员等级" prop="level_id">
                        <el-select v-model="fenxiaoTable.searchParam.level_id" class="input-width" clearable placeholder="请选择会员等级">
                            <el-option v-for="item in config.levelList" :key="item.value" :label="item.level_name" :value="item.level_id" />
                        </el-select>
                    </el-form-item>
                    <el-form-item label="状态" prop="status">
                        <el-select v-model="fenxiaoTable.searchParam.status" class="input-width" clearable placeholder="请选择状态">
                            <el-option v-for="item in config.statusList" :key="item.value" :label="item.label" :value="item.value" />
                        </el-select>
                    </el-form-item>
                    <el-form-item label="事业部合伙人" prop="is_top_area">
                        <el-checkbox v-model="isTopAreaChecked">是</el-checkbox>
                    </el-form-item>
                    <el-form-item label="创建时间" prop="create_time">
                        <el-date-picker v-model="fenxiaoTable.searchParam.create_time" type="datetimerange"
                            value-format="YYYY-MM-DD HH:mm:ss" start-placeholder="起始时间"
                            end-placeholder="结束时间" />
                    </el-form-item>
                    <el-form-item>
                        <el-button type="primary" @click="getFenxiaoPageFn()">搜索</el-button>
                        <el-button @click="resetForm(searchFormRef)">重置</el-button>
                    </el-form-item>
                </el-form>
            </el-card>

            <el-table :data="fenxiaoTable.data" size="large" v-loading="fenxiaoTable.loading" ref="goodsListTableRef">
                <template #empty>
                    <span>{{ !fenxiaoTable.loading ? '暂无数据' : '' }}</span>
                </template>
                <el-table-column prop="goods_id" label="用户名" min-width="200">
                    <template #default="{ row }">
                        <div class="flex items-center cursor-pointer" @click="toMember(row.member_id)">
                            <div class="min-w-[50px] h-[50px] flex items-center justify-center">
                                <el-image v-if="row.headimg" class="w-[50px] h-[50px]" :src="img(row.headimg)" fit="contain">
                                    <template #error>
                                        <div class="image-slot">
                                            <img class="w-[50px] h-[50px]" src="@/app/assets/images/member_head.png" alt="">
                                        </div>
                                    </template>
                                </el-image>
                                <img class="w-[50px] h-[50px]" v-else src="@/app/assets/images/member_head.png" alt="">
                            </div>
                            <div class="ml-2">
                                <span :title="row.username" class="multi-hidden">{{row.username || '--'}}</span>
                                <el-tag v-if="row.is_top_area == 1" type="success" size="mini">事业部合伙人</el-tag>
                            </div>
                        </div>
                    </template>
                </el-table-column>
                <!-- <el-table-column prop="nickname" label="会员昵称" min-width="170" /> -->
                <el-table-column prop="mobile" label="手机号" min-width="170" />
                <el-table-column label="会员等级" min-width="170">
                    <template #default="{ row }">
                        <div v-if="row.fenxiao_level" class="cursor-pointer price-wrap" @click="editLevelEvent(row)">
                            <span>{{row.fenxiao_level.level_name}}</span>
                            <el-icon class="ml-[5px]" :size="14"><EditPen /></el-icon>
                        </div>
                    </template>
                </el-table-column>
                <el-table-column label="上级" min-width="170">
                    <template #default="{ row }">
                        {{ row.parent_member?.username || '无' }}
                    </template>
                </el-table-column>
                <el-table-column label="团队累计消费金额" min-width="150">
                    <template #default="{ row }">
                        {{moneyFormat(row.total_team_consume)}}
                    </template>
                </el-table-column>
                <el-table-column prop="big_area" label="大区业绩" min-width="150" />
                <el-table-column prop="small_area" label="小区业绩" min-width="150" />
                <el-table-column prop="create_time" label="创建时间" min-width="120">
                    <template #default="{ row }">
                        {{row.create_time}}
                    </template>
                </el-table-column>
                <el-table-column prop="sort" label="状态" min-width="100">
                    <template #default="{ row }">
                        {{ row.status == 1 ? '正常' :'已冻结' }}
                    </template>
                </el-table-column>
                <el-table-column label="操作" fixed="right" align="right" min-width="120">
                    <template #default="{ row }">
                        <el-button type="primary" link @click="detailEvent(row)">详情</el-button>
                        <el-button v-if="row.status===1" type="primary" link @click="freezeOrRestoreEvent(row)">冻结</el-button>
                        <el-button v-if="row.status===-1" type="primary" link @click="freezeOrRestoreEvent(row)">恢复</el-button>
                    </template>
                </el-table-column>
            </el-table>
            <div class="mt-[16px] flex justify-end">
                <el-pagination v-model:current-page="fenxiaoTable.page" v-model:page-size="fenxiaoTable.limit"
                    layout="total, sizes, prev, pager, next, jumper" :total="fenxiaoTable.total"
                    @size-change="getFenxiaoPageFn(1)" @current-change="getFenxiaoPageFn" />
            </div>
            <!-- 编辑等级弹窗 -->
            <el-dialog v-model="fenxiaoLevelDialog" title="编辑等级" width="470px" :destroy-on-close="true" :close-on-click-modal="false">
                <div>
                    <el-form-item label="等级">
                        <el-select v-model="formData.level_id" class="input-width" clearable placeholder="请选择等级">
                            <el-option v-for="item in config.levelList" :key="item.value" :label="item.level_name" :value="item.level_id" />
                        </el-select>
                        <span class="text-[var(--el-color-primary)] ml-[10px] cursor-pointer" @click="getFenxiaoLevelListFn(true)">刷新</span>
                        <span class="text-[var(--el-color-primary)] ml-[10px] cursor-pointer" @click="addLevelFn">添加等级</span>
                    </el-form-item>
                </div>
                <template #footer>
                    <span class="dialog-footer">
                        <el-button @click="fenxiaoLevelDialog=false">取消</el-button>
                        <el-button type="primary" @click="fenxiaoLevelSubmit">确认</el-button>
                    </span>
                </template>
            </el-dialog>
            <!-- 选择团队绩效奖励弹窗 -->
            <fenxiao-of-select-popup title="编辑上级" ref="fenxiaoOfSelectPopupRef" :params="params" @load="selectFenxiaoCallbackFn" />
            <!-- 团队绩效奖励详情弹窗 -->
            <fenxiao-detail ref="fenxiaoDetailDialog" @load="getFenxiaoPageFn" />
        </el-card>
    </div>
</template>

<script lang="ts" setup>
import { ref, reactive, computed } from 'vue'
import { t } from '@/lang'
import { img, moneyFormat, setTablePageStorage, getTablePageStorage } from '@/utils/common'
import { cloneDeep } from 'lodash-es'
import { getFenxiaoLevelList, getFenxiaoPage, editFengxiao, getFenxiaoApplayStatus } from '@/app/api/range'
import { ElMessage, ElMessageBox, FormInstance } from 'element-plus'
import { useRoute, useRouter } from 'vue-router'
import fenxiaoDetail from '@/app/views/range/member/components/fenxiao-detail.vue'
import fenxiaoOfSelectPopup from '@/app/views/range/member/components/fenxiao-of-select-popup.vue'

const route = useRoute()
const router = useRouter()
const pageName = route.meta.title

const config :Record<string, any> = reactive({
    levelList: [],
    statusList: [
        { label: '正常', value: 1 },
        { label: '已冻结', value: -1 }
    ],
    applyStatus: []
})
// 弹窗
const fenxiaoLevelDialog = ref(false)

const fenxiaoTable = reactive({
    page: 1,
    limit: 10,
    total: 0,
    loading: false,
    data: [{}],
    searchParam: {
        keyword: '',
        level_id: '',
        status: '',
        is_top_area: null,
        create_time: [],
    }
})

// 事业部合伙人复选框
const isTopAreaChecked = computed({
    get: () => fenxiaoTable.searchParam.is_top_area === 1,
    set: (val: boolean) => {
        fenxiaoTable.searchParam.is_top_area = val ? 1 : (null as any)
    }
})

const getFenxiaoPageFn = (page: number = 1) => {
    fenxiaoTable.loading = true
    fenxiaoTable.page = page
    getFenxiaoPage({
        page: fenxiaoTable.page,
        limit: fenxiaoTable.limit,
        ...fenxiaoTable.searchParam
    }).then((res:any) => {
        fenxiaoTable.data = res.data.data
        fenxiaoTable.total = res.data.total
        fenxiaoTable.loading = false
        setTablePageStorage(fenxiaoTable.page, fenxiaoTable.limit, fenxiaoTable.searchParam)
    }).catch(() => {
        fenxiaoTable.loading = false
    })
}
getFenxiaoPageFn(getTablePageStorage(fenxiaoTable.searchParam).page)
// 获取分销等级
const getFenxiaoLevelListFn = (bool=false) => {
    getFenxiaoLevelList({
        page: 1,
        limit: 11,
        type: 2
    }).then((res: any) => {
        config.levelList = res.data.data
        if (bool) {
            ElMessage.success('刷新成功')
        }
    })
}
getFenxiaoLevelListFn()

// 跳转分销等级列表页面
const addLevelFn = ()=>{
    const routeData = router.resolve('/range/level')
    window.open(routeData.href)
}
// 获取团队绩效奖励申请状态
const getFenxiaoApplayStatusFn = () => {
    getFenxiaoApplayStatus().then(res => {
        config.applyStatus = res.data
    })
}
getFenxiaoApplayStatusFn()
const formData: Record<string, any> = reactive({
    id: 0,
    level_id: null,
    parent: null,
    status: 1
})
const params:Record<string, any> = reactive({
    member_id: formData.parent,
    is_agent: 'all'
})
const setFormData = (value:any) => {
    const data = cloneDeep(value)
    formData.id = data.member_id
    formData.level_id = data.level_id
    formData.parent = data.parent
    params.member_id = data.member_id
    formData.status = data.status
}
// 打开团队绩效奖励等级弹框
const editLevelEvent = (data:any) => {
    setFormData(data)
    fenxiaoLevelDialog.value = true
}
// 编辑分销等级回调
const fenxiaoLevelSubmit = () => {
    fenxiaoLevelDialog.value = false
    if (!formData.level_id) {
        ElMessage.error('请选择等级')
        return
    }
    fenxiaoSubmit()
}
// 选择上级团队绩效奖励弹框
const fenxiaoOfSelectPopupRef = ref<any>()
const editSupEvent = (row:any) => {
    setFormData(row)
    fenxiaoOfSelectPopupRef.value?.show()
}
// 选择回调
const selectFenxiaoCallbackFn = (row: any) => {
    if (row && row.member_id) {
        formData.parent = row.member_id
        formData.parent_name = row.username
    } else {
        formData.parent = ''
        formData.parent_name = ''
    }
    ElMessageBox.confirm('确认要变更上级吗', '提示',
        {
            confirmButtonText: t('confirm'),
            cancelButtonText: t('cancel'),
            type: 'warning'
        }
    ).then(() => {
        fenxiaoSubmit()
    })
}
// 冻结
const freezeOrRestoreEvent = (row:any) => {
    setFormData(row)
    ElMessageBox.confirm(formData.status === 1 ? '确认冻结改该账户吗' : '确认恢复改该账户吗', '提示',
        {
            confirmButtonText: t('confirm'),
            cancelButtonText: t('cancel'),
            type: 'warning'
        }
    ).then(() => {
        formData.status = formData.status === 1 ? -1 : 1
        fenxiaoSubmit()
    })
}
const fenxiaoSubmit = () => {
    editFengxiao(formData).then(() => {
        getFenxiaoPageFn()
    })
}
// 查看团队绩效奖励详情
const fenxiaoDetailDialog: Record<string, any> | null = ref(null)
const detailEvent = (row:any) => {
    setFormData(row)

    let data = { id: formData.id }
    fenxiaoDetailDialog.value.setFormData(data);
    fenxiaoDetailDialog.value.showDialog = true
}
// 重置查询
const searchFormRef = ref()
const resetForm = (formEl: FormInstance | undefined) => {
    if (!formEl) return
    formEl.resetFields()
    getFenxiaoPageFn()
}

// 跳转会员详情
const toMember = (id:number) => {
    const routeData = router.resolve(`/member/detail?id=${id}`)
    window.open(routeData.href, '_blank')
}
</script>

<style lang="scss" scoped></style>
